<template>
	<view>

		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel"
			@AddModuleData_select='AddModuleData_select'>
			<template #workbench>

				<m-drag-button :style="{ opacity: BtnShow ? 1 : 0 }" :isDock="true" :existTabBar="true"
					class="m-drag-button-view" :initialBottom="60">
					<template #BtnContent>
						<u-icon name="search" color="#fff" size="25px" @click="search"></u-icon>
					</template>
				</m-drag-button>

			</template>
			<template #content>
				<view class="content_box f-dc">
					<view class="table table_top_th">
						<table>
							<tr>
								<th width='20%'>模具</th>
								<th width='23%'>设备</th>
								<th width='20%'>产品</th>
								<th width='10%'>上模人员</th>
								<th width='20%'>上模开始时间</th>
								<th width='7%'>操作</th>
							</tr>
						</table>
					</view>
					<z-paging ref="paging" v-model="dataList" @query="queryList" :fixed="false" class="z_paging">
						<view class="table">
							<table class="table-full">
								<tbody>
									<tr style="border: 1px solid #ccc;" v-for="(item,index) in dataList" :key="index"
										@click="itemClick(item,index)">

										<td width='20%'>
											<view class="ListTdDiv"><text>{{item.MoldNO}}</text></view>
										</td>
										<td width='23%'>
											<view class="ListTdDiv"><text>{{item.EquipmentCode}}</text></view>
										</td>
										<td width='20%'>
											<view class="newlineDiv"><text>{{item.ProductName}}</text></view>
										</td>
										<td width='10%'>
											<view class="ListTdDiv"><text>{{item.EmpolorName}}</text></view>
										</td>
										<td width='20%'>
											<view class="ListTdDiv"><text>{{item.StartTime}}</text></view>
										</td>
										<td width='7%' @click.stop style="padding: 5px;box-sizing: border-box;">
											<u-button text="上下模" color="#dbb56a" v-show="item.AStatus==0"
												@click="addoperate(item,index)"></u-button>
										</td>
									</tr>
								</tbody>
							</table>
						</view>
					</z-paging>
				</view>
				<!-- 	<view class="add">
					<u-icon name="plus" color="#fff" size="30" @click="add"></u-icon>
				</view> -->
				<view class="search">
					<u-icon name="search" color="#fff" size="30" @click="search"></u-icon>
				</view>

				<uni-popup ref="popup" type="bottom" background-color="#fff" border-radius="10px 10px 0 0"
					@change="changePopup">
					<view class="popup_content">

						<u-cell-group :border='false'>
							<u-cell title="开始时间" :isLink="false" :value='FormData.FBDate'
								@click="addTime('开始')"></u-cell>
							<u-cell title="结束时间" :isLink="false" :value='FormData.FEDate'
								@click="addTime('结束')"></u-cell>

						</u-cell-group>
						<view class="bottomBtns">
							<button block @click="submit">
								查 &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp 询
							</button>
						</view>

					</view>
				</uni-popup>

				<u-datetime-picker :show="show" v-model="value1" mode="date" @cancel='show = false'
					@confirm='pickerConfirm'></u-datetime-picker>

				<u-popup :show="operateobjshow" mode="center" @close="operateobjclose" @open="operateobjopen"
					:round="10">
					<view class="popupShowList">
						<view class="table table_top_th  table_popup_top_th">
							<table>
								<tr>
									<th width='5%'></th>
									<th width='25%'>派单单号</th>
									<th width='15%'>派工日期</th>
									<th width='15%'>产品名称</th>
									<th width='30%'>产品型号</th>
									<th width='10%'>数量</th>
								</tr>

							</table>
						</view>

						<z-paging ref="PopupQueryPaging" v-model="dispatchinglist" @query="PopupQueryList"
							:fixed="false" class="z_paging" :style="{ height: scrollLiftHeight + 'px'}">
							<view class="table" style="overflow-x: auto;width: 100%;">
								<table>
									<tbody>
										<tr v-for="(item,index) in dispatchinglist">
											<td width='5%'>
												<checkbox-group @change="toggleSelect(item.id)" @click.stop>
													<checkbox :checked="selectedItems.includes(item.id)"
														:disabled="shouldDisableCheckbox(item)"></checkbox>
												</checkbox-group>
											</td>
											<td width='25%'>
												<view class="newlineDiv"><text>{{item.BillNO}}</text></view>
											</td>
											<td width='15%'>
												<view class="ListTdDiv"><text>{{item.BillDate}}</text></view>
											</td>
											<td width='15%'>
												<view class="newlineDiv"><text>{{item.ProductName}}</text></view>
											</td>
											<td width='30%'>

												<view class="newlineDiv"><text>{{item.ProductSpec}}</text></view>
											</td>

											<td width='10%'>
												<view class="ListTdDiv"><text>{{item.FPlanQty}}</text></view>
											</td>
										</tr>

									</tbody>
								</table>

							</view>
							<view class="bottomBtns2">
								<button class="button1" block @click="Upperlower">
									一键上下模
								</button>

							</view>
						</z-paging>

					</view>
				</u-popup>

				<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm'>
					<view class="slot-content">
						{{modalcontent}}
					</view>
				</u-modal>



				<u-toast ref="uToast"></u-toast>
			</template>

		</st-mc-framework>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>

<script>
	import {
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';

	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {
				modalshow: false,
				modaltitle: '提示',
				modalcontent: '',
				confirmText: '确认',



				dataList: [],

				FormData: {
					PageIndex: 1,
					PageSize: 30,
					FBDate: '',
					FEDate: '',
					ChangeMoldType: 0,
				},
				APPFunID: 0,
				tabIndex: 0,
				showLeft: false,
				TimeName: '',
				show: false,
				value1: Number(new Date()),

				disabled: false,

				operateobj: {},
				operateobjIndex: null,
				operateobjshow: false,

				dispatchingFormData: {
					PageIndex: 1,
					PageSize: 30,
					FBDate: '',
					FEDate: '',
					ChangeMoldType: 1,
				},
				scrollLiftHeight: uni.getSystemInfoSync(), //列表高度
				dispatchinglist: [],
				selectedItems: [], // 存储选中行的索引
				loadingPage: false,
				loadingName: '',
				ModuleTitle: '',
				showMLoading: false, //是否加载
				loadingName: '正在加载中……', //加载名称
				BtnShow: false, //按钮显示
			}

		},
		computed: {

		},
		onShow() {
			var that = this
			uni.$on('refreshList', () => {
				this.getList(); // 调用目标方法
			});
		},
		onUnload() {
			uni.$off('refreshList');
		},
		onReady() {
			var that = this
			uni.hideLoading();
			that.showMLoading = true
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName

			that.$nextTick(() => {
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
		},
		onLoad(options) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			if (options.Dispatchitem) {
				const dispatchItem = JSON.parse(options.Dispatchitem);
				that.assignFormData(that.FormData, dispatchItem);
				return;
			}
			const formDefaults = {
				FBDate: getBefore7DateTime(),
				FEDate: getFormatDateTime(new Date()),
			};
			that.assignFormData(that.FormData, formDefaults);
		},
		methods: {
			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},
			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},
			modalconfirm() {
				var that = this
				that.modalshow = false
			},
			shouldDisableCheckbox(item) {
				return !this.selectedItems.includes(item.id) && this.selectedItems.length > 0;
			},
			toggleSelect(id) {
				const index = this.selectedItems.indexOf(id)
				if (index > -1) {
					this.selectedItems.splice(index, 1) // 修正第二个参数为1
				} else {
					this.selectedItems.push(id)
				}
				console.log(this.selectedItems);
			},

			Upperlower() {
				var that = this
				if (that.selectedItems.length > 0) {
					const selectedSet = new Set(this.selectedItems)
					const filteredData = this.dispatchinglist.filter(item =>
						selectedSet.has(item.id)
					)
					console.log(filteredData);
					var obj = {
						WhiteORNight: that.operateobj.WhiteORNight,
						ZSChangeMoldID: that.operateobj.ZSChangeMoldID,
						MoludID: that.operateobj.MoludID,
						JobOrderID: filteredData.map(item => item.JobOrderID).join('~')
					}
					console.log(obj)


					that.Request.request('ZS_YJSXM', obj, function(ret) {
						console.log(ret);
						if (ret.data.ds[0] && ret.data.ds[0].status == 200) {
							that.operateobjshow = false
							that.selectedItems = []
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: ret.data.ds[0].msg
							})
						} else {
							that.showModal('提示', ret.data.ds[0].msg);
						}
					})

				} else {
					uni.showToast({
						title: '请选中一行',
						icon: 'error',
						duration: 2000
					})
				}


			},
			operateobjclose() {
				var that = this
				that.operateobjshow = false
				that.selectedItems = []
			},
			operateobjopen() {
				var that = this
				this.$nextTick(() => {
					var scrollLiftHeight
					uni.createSelectorQuery().select('.popupShowList').boundingClientRect(data => {
						console.log(data.height);
						scrollLiftHeight = data.height;
						uni.createSelectorQuery().select('.table_popup_top_th').boundingClientRect(res => {
							console.log(res.height);
							that.scrollLiftHeight = scrollLiftHeight - res.height;

						}).exec()
					}).exec()
				});


			},
			addoperate(item, index) {
				var that = this
				console.log(item);
				that.operateobjIndex = index
				that.operateobj = item
				if (that.operateobj.JobOrderID == null || that.operateobj.JobOrderID == undefined ||
					that.operateobj.JobOrderID == '') {
					that.operateobj.JobOrderID = 0
				}
				var obj = {
					JobOrderID: that.operateobj.JobOrderID,
					MoludID: that.operateobj.MoludID
				}
				console.log(obj);
				that.Request.request('getMoludJobOrderList', obj, function(ret) {
					console.log(ret)
					if (ret.status == 200) {
						if (ret.data.ds[0] && ret.data.ds[0].status == 500) {
							that.showModal('提示', ret.data.ds[0].msg);
						} else {
							that.operateobjshow = true
						}

					}
				})

			},
			PopupQueryList() {
				let that = this;
				if (that.operateobj.JobOrderID == null || that.operateobj.JobOrderID == undefined ||
					that.operateobj.JobOrderID == '') {
					that.operateobj.JobOrderID = 0
				}
				var obj = {
					JobOrderID: that.operateobj.JobOrderID,
					MoludID: that.operateobj.MoludID
				}
				that.Request.request('getMoludJobOrderList', obj, function(ret) {
					console.log(ret)
					if (ret.status == 200) {
						if (ret.data.ds[0] && ret.data.ds[0].status == 500) {
							that.showModal('提示', ret.data.ds[0].msg);
						} else {
							ret.data.ds.map(item => item.BillDate = formatDateTime(item.BillDate))
							ret.data.ds.forEach((item, index) => {
								item.id = index
							})
							that.$refs.PopupQueryPaging.complete(ret.data.ds);

						}

					}
				})


			},

			getList() {
				this.contents = []; // 假设这是异步获取数据的操作
				this.$refs.paging.reload();
			},


			addTime(name) {
				this.TimeName = name
				if (this.TimeName == '开始') {
					this.value1 = Number(getTimeStamp(this.FormData.FBDate))
				} else {
					this.value1 = Number(getTimeStamp(this.FormData.FEDate))
				}
				this.show = true
			},

			pickerConfirm(e) {
				var time = getFormatDateTime(e.value)
				if (this.TimeName == '开始') {
					this.FormData.FBDate = time
				} else {
					this.FormData.FEDate = time
				}
				this.show = false
			},

			changePopup() {

			},
			search() {
				this.$refs.popup.open('bottom')

			},
			submit() {

				this.$refs.popup.close('bottom')
				this.contents = []; // 假设这是异步获取数据的操作
				this.$refs.paging.reload();
			},
			add() {
				let routes = getCurrentPages();
				var url = '/st_mes_zs/poweron/upMoldDetail'
				let obj = {
					Name: '上模详情',
					APPFunID: '上模详情',
					path: 'manual',
					length: routes.length + 1,
					url: url,
				}
				this.GonavigateTo(obj, url)
			},
			queryList(pageNo) {
				let that = this;
				that.FormData.PageIndex = pageNo
				try {
					that.Request.request('getZSChangeMoldList', that.FormData, (ret) => {
						console.log(ret);
						if (ret.status == 200) {
							that.showMLoading = false
							ret.data.ds.map((item) => {
								item.StartTime = formatDateTime(item.StartTime)
							})
							that.$refs.paging.complete(ret.data.ds);
						} else {
							that.showMLoading = false
						}
					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					console.log(e)
					that.showMLoading = false
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},

			itemClick(item, index) {
				let routes = getCurrentPages();

				var url = `/st_mes_zs/poweron/upMoldDetail?ZSChangeMoldID=${item.ZSChangeMoldID}`
				let obj = {
					Name: '上模详情',
					APPFunID: '上模详情',
					path: 'manual',
					length: routes.length + 1,
					url: url,
				}
				this.GonavigateTo(obj, url)
			},

			GonavigateTo(obj, url) {
				let that = this;
				var initData = JSON.parse(JSON.stringify(that.$store.state.GuyueModule.ModuleData_select));
				var parentData = initData[initData.length - 1]
				parentData.url = `/st_mes_zs/poweron/upMold?Dispatchitem=${JSON.stringify(that.FormData)}`;
				that.$modifyParentData(parentData);
				this.$safeNavigate({
					targetUrl: url, // 目标页面路径
					payload: obj, // 要传递的数据
				});
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			changeLevel(list, data, row) {
				getchangeLevel(data)

			},
		},


		onNavigationBarButtonTap(e) {
			if (this.showLeft) {
				this.$refs.showLeft.close()
			} else {
				this.$refs.showLeft.open()
			}
		},
		// app端拦截返回事件 ，仅app端生效
		onBackPress() {
			if (this.showRight || this.showLeft) {
				this.$refs.showLeft.close()
				this.$refs.showRight.close()
				return true
			}
		}
	}
</script>

<style lang="scss" >
	@import "../css/index.css";

	.popupShowList {
		width: 90vw;
		height: 60vh;

		background-color: #fff;

		font-size: 14px;
		border-radius: 4px !important;

		.popupText {

			white-space: normal;
			word-wrap: break-word;
			word-break: break-all;
		}

		.popupText text {
			font-size: 14px;
		}
	}

	.bottomBtns2 {
		padding-top: 5px;
		width: 100%;
		display: flex;

		button {
			display: inline-block;
			color: #fff;
			background-color: #51d0d0;
			width: 20%;
			font-size: 16px;
		}

	}

	/* 修复复选框样式 */
	checkbox .wx-checkbox-input,
	checkbox .uni-checkbox-input {
		// border-radius: 50% !important;
		transform: scale(0.9);
	}

	checkbox .wx-checkbox-input.wx-checkbox-input-checked,
	checkbox .uni-checkbox-input.uni-checkbox-input-checked {
		background: #007aff !important;
		border-color: #007aff !important;
	}
</style>